from fastapi import Request
from pydantic import BaseModel
from tortoise.transactions import atomic, in_transaction

from service import UserService
from service import RepositoryService
from common.result.Result import Result
from common.enum import BaseEnum
from util.str import Str
from util.log import Log
from util.token import Token
from util.time import Time

async def CreateRepository(req: Request, body: dict = None):
    try:
        async with in_transaction() as connection:
            token = req.headers.get("token")
            if Str.isBlank(token):
                Log.error('参数为空，检查参数')
                return Result.error(BaseEnum.PARAMETER_INVALID_ERROR)
            
            user = await UserService.getUserByToken(token)
            if user == None:
                Log.error('user 不存在', user)
                return Result.error(BaseEnum.USER_NOT_EXISTS_ERROR)

            # 构造 repository
            repository = {
                "id": Time.getUTC8Timestamp(),
                "icon": 'https://varitall.oss-cn-beijing.aliyuncs.com/icon/repository-default-icon.png',
                "user_id": user.id,
                "title": '默认标题',
                "short_uri": await uniqueShortUri(8),
                "permission": 2, # 默认公开
                "description": '你可以点击左边菜单的 + 号，添加新的文档'
            }

            result = await RepositoryService.createRepository(repository)
            
            return Result.success(result)
    except Exception as e:
        Log.error('创建知识库异常', e)
        return Result.error(BaseEnum.SERVICE_ERROR)

async def uniqueShortUri(len: int):
    objList = await RepositoryService.allShortUriList()
    shortUriList = [item.get('short_uri') for item in objList]

    shortUri = Str.generateRandomString(len)
    while shortUri in shortUriList:
        shortUri = Str.generateRandomString(len)
        
    return shortUri